package com.test.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.test.bean.Yellow;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/11/29 14:23
 * <p>
 * spring提供的可以根据当前环境，动态的激活和切换一些列组件的功能
 * 开发环境，测试环境，生产环境
 * 数据源（A,B,C）
 * @Profile: 指定组件在哪个环境的情况下才能被注册到容器中，不指定，任何环境下都能注册这个组件
 * 1.加了环境标识的bean，只有这个环境激活的时候才能注册到容器中,默认是default环境
 * 2.写在配置类上，只有是指定的环境的时候，整个配置类里面的所有配置才能开始生效
 * 3.没有标注环境标志的bean在任何环境下都是加载的
 */
//@Profile("test")
@PropertySource("classpath:db.properties")
@Configuration
public class MainConfigProfile implements EmbeddedValueResolverAware {

    @Value("${jdbc.user}")
    private String user;

    private StringValueResolver resolver;

    @Bean
    public Yellow yellow() {
        return new Yellow();
    }

    @Profile("default")
    @Bean("devDataSource")
    public DataSource dataSourceDev(@Value("${jdbc.passowrd}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl(resolver.resolveStringValue("${jdbc.url}"));
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }

    @Profile("test")
    @Bean("testDataSource")
    public DataSource dataSourceTest(@Value("${jdbc.passowrd}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl(resolver.resolveStringValue("${jdbc.url}"));
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }

    @Profile("product")
    @Bean("productDataSource")
    public DataSource dataSourceProduct(@Value("${jdbc.passowrd}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl(resolver.resolveStringValue("${jdbc.url}"));
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.resolver = resolver;
    }
}
